package com.grj.community.all.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.grj.community.all.common.RedisKey;
import com.grj.community.all.common.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 14505
 */
@RestController
@RequestMapping("/sign")
@RequiredArgsConstructor
public class SignController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private final HttpServletResponse httpServletResponse;


    @GetMapping
    public Boolean sign(){
        String uid = httpServletResponse.getHeader("uid");
        String now = DateUtil.now();
        String[] s = now.split(" ");
        String[] split = s[0].split("-");
        return redisTemplate.opsForValue().setBit(RedisKey.SIGN+uid+":"+split[0]+split[1], Integer.parseInt(split[2])+1, true);
    }

    @GetMapping("signs")
    public Result<Object> signs(){
        String uid = httpServletResponse.getHeader("uid");
        String now = DateUtil.now();
        String[] s = now.split(" ");
        String[] split = s[0].split("-");
        String key = RedisKey.SIGN+uid+":"+split[0]+split[1];
        List<Long> longs = redisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(Integer.parseInt(split[2]))).valueAt(0));
        System.out.println(longs);
        if(Objects.isNull(longs) || longs.size() == 0){
            return Result.success("666");
        }
        int i=0;
        Long l = longs.get(i);
        while (true){
            if((l & 1) == 0){
                break;
            }else {
                i++;
            }
            l >>>=1;
        }
        return Result.success(i);
    }

    @GetMapping("view")
    public Result<Object> view(){
        String uid = httpServletResponse.getHeader("uid");
        Long increment = redisTemplate.opsForHash().increment(RedisKey.VIEW+DateUtil.now(), uid, 1);
//        System.out.println(redisTemplate.opsForHash().get(RedisKey.VIEW+DateUtil.now(), uid));
//        Object o = redisTemplate.opsForHash().get(RedisKey.VIEW, uid);
//        System.out.println(o);
        return Result.success(increment);
    }

}
